package com.ruoyi.project.system.controller;


import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.upload.FileUploadTemplate;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysDirTree;
import com.ruoyi.project.system.domain.SysFile;
import com.ruoyi.project.system.service.ISysDirTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 系统目录树 前端控制器
 * </p>
 *
 * @author luaj
 * @since 2019-11-22
 */
@RestController
@RequestMapping("/system/dirtree")
public class SysDirTreeController extends BaseController {
    @Autowired
    private ISysDirTreeService dirTreeService;
    @Resource
    @Qualifier("CommonUpload")
    private FileUploadTemplate fileUploadTemplate;

    /**
     * 获取目录列表
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDirTree dirTree)
    {
        List<SysDirTree> dirTrees = dirTreeService.selectSysDirTreeList(dirTree);
        return AjaxResult.success(dirTreeService.builddirTreeTree(dirTrees));
    }

    /**
     * 根据目录编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:query')")
    @GetMapping(value = "/{dirTreeId}")
    public AjaxResult getInfo(@PathVariable Long dirTreeId)
    {
        return AjaxResult.success(dirTreeService.selectdirTreeById(dirTreeId));
    }

    /**
     * 获取目录下拉树列表
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:query')")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDirTree dirTree)
    {
        List<SysDirTree> dirTrees = dirTreeService.selectSysDirTreeList(dirTree);
        return AjaxResult.success(dirTreeService.builddirTreeTreeSelect(dirTrees));
    }

//    /**
//     * 加载对应角色目录列表树
//     */
//    @PreAuthorize("@ss.hasPermi('system:dirTree:query')")
//    @GetMapping(value = "/roledirTreeselect/{roleId}")
//    public AjaxResult roledirTreeTreeselect(@PathVariable("roleId") Long roleId)
//    {
//        return AjaxResult.success(dirTreeService.selectdirTreeListByRoleId(roleId));
//    }

    /**
     * 新增目录
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:add')")
    @Log(title = "目录管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDirTree dirTree)
    {
        if (UserConstants.NOT_UNIQUE.equals(dirTreeService.checkdirTreeNameUnique(dirTree)))
        {
            return AjaxResult.error("新增目录'" + dirTree.getDirName() + "'失败，目录名称已存在");
        }
        dirTree.setCreateBy(SecurityUtils.getUsername());
        return toAjax(dirTreeService.insertdirTree(dirTree));
    }

    /**
     * 修改目录
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:edit')")
    @Log(title = "目录管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDirTree dirTree)
    {
        if (UserConstants.NOT_UNIQUE.equals(dirTreeService.checkdirTreeNameUnique(dirTree)))
        {
            return AjaxResult.error("修改目录'" + dirTree.getDirName() + "'失败，目录名称已存在");
        }
        else if (dirTree.getParentId().equals(dirTree.getDirId()))
        {
            return AjaxResult.error("修改目录'" + dirTree.getDirName() + "'失败，上级目录不能是自己");
        }
        dirTree.setUpdateBy(SecurityUtils.getUsername());
        dirTree.setUpdateTime(new Date());
        return toAjax(dirTreeService.updatedirTree(dirTree));
    }

    /**
     * 删除目录
     */
    @PreAuthorize("@ss.hasPermi('system:dirTree:remove')")
    @Log(title = "目录管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dirTreeId}")
    public AjaxResult remove(@PathVariable Long dirTreeId)
    {
        if (dirTreeService.hasChildBydirTreeId(dirTreeId))
        {
            return AjaxResult.error("存在下级目录,不允许删除");
        }
        if (dirTreeService.checkdirTreeExistChild(dirTreeId))
        {
            return AjaxResult.error("目录存在子对象,不允许删除");
        }
        return toAjax(dirTreeService.deletedirTreeById(dirTreeId));
    }

    @PreAuthorize("@ss.hasPermi('system:dirTree:edit')")
    @Log(title = "文件上传", businessType = BusinessType.UPLOAD)
    @PostMapping("/uploadfile")
    public AjaxResult uploadfile(MultipartFile file, HttpServletRequest request) throws IOException, InvalidExtensionException {
        if(file==null){
            return AjaxResult.error("请上传文件");
        }
        return AjaxResult.success(fileUploadTemplate.template(file, new SysFile()));
    }

}
